#include "HttpRouter.h"
#include <cassert>
#include <cerrno>

extern "C" {
#include "rax/rax.h"
}

Router::Router()
{
	m_rtRouter.reset(raxNew(), [](rax *pRax) {
		pRax != nullptr ? raxFree(pRax) : (void)0;
	});
	assert(m_rtRouter);
}

Router::~Router()
{
}

bool Router::Add(const std::string& uri, callback_type cb)
{
	int nIdx = m_vecCallback.size();
	void* extra = nullptr;
	*(reinterpret_cast<int *>(&extra)) = nIdx;
	int nRes = 0;
	if ((nRes = raxInsert(m_rtRouter.get(), (unsigned char*)(const_cast<char*>(uri.data())), uri.length(), extra, nullptr)) != 0) {
		m_vecCallback.push_back(cb);
		return true;
	}
	return false;
}

bool Router::Lookup(const std::string& uri, callback_type& cb)
{
	void* data = raxFind(m_rtRouter.get(), (unsigned char*)(const_cast<char*>(uri.data())), uri.length());
	if (data != raxNotFound) {
		int nIdx = *(reinterpret_cast<int*>(&data));
		assert(m_vecCallback.size() > nIdx);
		cb = m_vecCallback[nIdx];
		return true;
	}
	return false;
}
